package luj.tool.jnproxyan.proxy.network.socks.cmd.connect;

import io.netty.buffer.ByteBuf;
import luj.net.api.server.ConnectionAcceptInitializer;
import luj.net.api.server.FrameDataReceiver;

final class P2sReceiver implements FrameDataReceiver {

  P2sReceiver(ConnectionAcceptInitializer.Connection c2pConn) {
    _c2pConn = c2pConn;
  }

  @Override
  public Result receive(Context ctx) throws Exception {
    ByteBuf frameBuf = ctx.getLastFrame();
    forwardToClient(frameBuf);

    return ctx.then()
        .nextReceiver(this);
  }

  private void forwardToClient(ByteBuf frameBuf) {
    if (frameBuf == null) {
      return;
    }

    frameBuf.retain();

    _c2pConn.write(frameBuf);
    _c2pConn.flush();
  }

  private final ConnectionAcceptInitializer.Connection _c2pConn;
}
